package com.hlt.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Assert;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hlt.context.BaseContext;
import com.hlt.dto.CommentsDTO;
import com.hlt.dto.CommentsPageQueryDTO;
import com.hlt.entity.Comments;
import com.hlt.entity.Users;
import com.hlt.entity.Posts;
import com.hlt.mapper.CommentsMapper;
import com.hlt.mapper.UsersMapper;
import com.hlt.mapper.PostsMapper;
import com.hlt.result.PageResult;
import com.hlt.service.ICommentsService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hlt.utils.CommentsConvertUtil;
import com.hlt.vo.CommentsVO;
import com.hlt.utils.SensitiveWordUtil;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.beans.factory.annotation.Autowired;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import static com.hlt.utils.CommentsConvertUtil.convertToVOList;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author lzf
 * @since 2024-11-25
 */
@Service
public class CommentsServiceImpl extends ServiceImpl<CommentsMapper, Comments> implements ICommentsService {

        @Autowired
        private UsersMapper usersMapper;

        @Autowired
        private PostsMapper postsMapper;

        @Autowired
        private SensitiveWordUtil sensitiveWordUtil;

        @Override
        public PageResult pageQuery(CommentsPageQueryDTO commentsPageQueryDTO) {
                // 构建分页对象
                Page<Comments> page = new Page<>(commentsPageQueryDTO.getPageNum(), commentsPageQueryDTO.getPageSize());

                // 构建查询条件
                LambdaQueryWrapper<Comments> queryWrapper = new LambdaQueryWrapper<>();
                queryWrapper.eq(commentsPageQueryDTO.getUserId() != null, Comments::getUserId,
                                commentsPageQueryDTO.getUserId())
                                .eq(commentsPageQueryDTO.getPostId() != null, Comments::getPostId,
                                                commentsPageQueryDTO.getPostId())
                                .like(commentsPageQueryDTO.getContent() != null, Comments::getContent,
                                                commentsPageQueryDTO.getContent())
                                .orderByDesc(Comments::getCreatedAt);

                // 执行分页查询
                page = page(page, queryWrapper);

                return new PageResult(page.getTotal(), page.getRecords());
        }

        @Override
        @Transactional
        public void addComment(CommentsDTO commentsDTO) {
                // 获取当前用户ID
                Long userId = BaseContext.getCurrentId();
                if (userId == null) {
                        throw new IllegalArgumentException("请先登录");
                }

                // 参数校验
                Assert.notNull(commentsDTO.getPostId(), "文章ID不能为空");
                Assert.notNull(commentsDTO.getContent(), "评论内容不能为空");
                if (commentsDTO.getContent().trim().isEmpty()) {
                        throw new IllegalArgumentException("评论内容不能为空");
                }

                // 敏感词检测与替换
                String originalContent = commentsDTO.getContent();
                String filteredContent = sensitiveWordUtil.replace(originalContent); // 直接替换敏感词
                commentsDTO.setContent(filteredContent); // 更新为过滤后的内容

                // 创建评论（使用过滤后的内容）
                Comments comment = new Comments();
                comment.setPostId(commentsDTO.getPostId());
                comment.setUserId(Math.toIntExact(userId));
                comment.setContent(filteredContent); // 使用过滤后的内容
                comment.setParentId(commentsDTO.getParentId());
                comment.setCreatedAt(LocalDateTime.now());
                comment.setIsDeleted(1);

                // 保存评论
                save(comment);

                // 更新文章评论数
                Posts post = postsMapper.selectById(commentsDTO.getPostId());
                if (post != null) {
                        post.setCommentsCount(post.getCommentsCount() + 1);
                        postsMapper.updateById(post);
                }
        }

        @Override
        @Transactional
        public void deleteComment(Integer commentId) {
                // 获取当前用户ID
                Long userId = BaseContext.getCurrentId();
                if (userId == null) {
                        throw new IllegalArgumentException("请先登录");
                }

                // 查询评论
                Comments comment = getById(commentId);
                if (comment == null) {
                        throw new IllegalArgumentException("评论不存在");
                }

                // 检查是否是评论作者
                if (!comment.getUserId().equals(Math.toIntExact(userId))) {
                        throw new IllegalArgumentException("只能删除自己的评论");
                }

                // 删除评论（软删除）
                comment.setIsDeleted(0);
                updateById(comment);
        }

        @Override
        public PageResult getUserComments(CommentsPageQueryDTO pageQueryDTO) {
                // 构建分页对象
                Page<Comments> page = new Page<>(pageQueryDTO.getPageNum(), pageQueryDTO.getPageSize());

                // 构建查询条件
                LambdaQueryWrapper<Comments> queryWrapper = new LambdaQueryWrapper<>();
                queryWrapper.eq(Comments::getUserId, pageQueryDTO.getUserId())
                                .eq(Comments::getIsDeleted, 1)
                                .orderByDesc(Comments::getCreatedAt);

                // 执行分页查询
                page = page(page, queryWrapper);

                // 获取所有用户ID
                List<Integer> userIds = page.getRecords().stream()
                                .map(Comments::getUserId)
                                .distinct()
                                .collect(Collectors.toList());

                // 查询用户信息
                List<Users> usersList = usersMapper.selectList(
                                new LambdaQueryWrapper<Users>().in(Users::getUserId, userIds));
                Map<Integer, Users> userMap = usersList.stream()
                                .collect(Collectors.toMap(Users::getUserId, user -> user));

                // 转换为VO对象
                List<CommentsVO> commentsVOList = convertToVOList(page.getRecords(), userMap);

                // 构建树形结构
                List<CommentsVO> tree = CommentsConvertUtil.buildCommentTree(commentsVOList);

                return new PageResult(page.getTotal(), tree);
        }

        @Override
        public PageResult getPostComments(CommentsPageQueryDTO pageQueryDTO) {
                // 构建分页对象
                Page<Comments> page = new Page<>(pageQueryDTO.getPageNum(), pageQueryDTO.getPageSize());

                // 构建查询条件
                LambdaQueryWrapper<Comments> queryWrapper = new LambdaQueryWrapper<>();
                queryWrapper.eq(Comments::getPostId, pageQueryDTO.getPostId())
                                .eq(Comments::getIsDeleted, 1)
                                .isNull(Comments::getParentId) // 只查询一级评论
                                .orderByDesc(Comments::getCreatedAt);

                // 执行分页查询
                page = page(page, queryWrapper);

                // 获取所有评论ID
                List<Integer> commentIds = page.getRecords().stream()
                                .map(Comments::getId)
                                .collect(Collectors.toList());

                // 查询所有子评论
                List<Comments> allComments = new ArrayList<>(page.getRecords());
                if (!commentIds.isEmpty()) {
                        LambdaQueryWrapper<Comments> childQueryWrapper = new LambdaQueryWrapper<>();
                        childQueryWrapper.eq(Comments::getPostId, pageQueryDTO.getPostId())
                                        .eq(Comments::getIsDeleted, 1)
                                        .in(Comments::getParentId, commentIds) // 关键：子评论的父ID匹配一级评论ID
                                        .orderByAsc(Comments::getCreatedAt);
                        List<Comments> childComments = list(childQueryWrapper);
                        allComments.addAll(childComments);
                }

                // 获取所有用户ID
                List<Integer> userIds = allComments.stream()
                                .map(Comments::getUserId)
                                .distinct()
                                .collect(Collectors.toList());

                // 查询用户信息
                List<Users> usersList = usersMapper.selectList(
                                new LambdaQueryWrapper<Users>().in(Users::getUserId, userIds));
                Map<Integer, Users> userMap = usersList.stream()
                                .collect(Collectors.toMap(Users::getUserId, user -> user));

                // 转换为VO对象
                List<CommentsVO> commentsVOList = convertToVOList(allComments, userMap);

                // 构建树形结构
                List<CommentsVO> tree = CommentsConvertUtil.buildCommentTree(commentsVOList);

                return new PageResult(page.getTotal(), tree);
        }

}
